package com.sl.au.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.Account;
import com.sl.au.entity.User;
import com.sl.au.repository.UserRepository;
import com.sl.au.service.AccountService;
import com.sl.au.service.UserService;

@Service("userService")
@Transactional
public class UserServiceImpl extends BaseServiceImpl implements UserService {

	@Autowired
	UserRepository userRepository;
	@Autowired
	AccountService accountService;

	@Override
	public List<User> getPage(int start, int length, String key, String orderName, String dir) {
		Page<User> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		pages = userRepository.findAll(pageable);
		return pages.getContent();
	}

	@Override
	public List<User> getUsers(int start, int length, String key, String orderName, String dir) {
		Page<User> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		pages = userRepository.getUserName(key, pageable);
		return pages.getContent();
	}

	public UserRepository getRepository() {
		return this.userRepository;
	}

	@Override
	public int getCount(String key) {
		if (!StringUtils.hasText(key))
			return userRepository.findAll().size();
		Pageable pageable = new PageRequest(0, Integer.MAX_VALUE, Sort.Direction.DESC, "createTime");
		return userRepository.getUserName(key, pageable).getContent().size();
	}

	@Override
	public void delete(String userId) {
		User user = this.getRepository().getOne(userId);
		if (null == user)
			return;
		user.setDisable(1);
		userRepository.save(user);
		accountService.getRepository().deleteByUser(user);
		//this.getRepository().delete(userId);

	}

	@Override
	public List<User> userByRole(String roleName) {
		List<User> users = this.getRepository().findAll();
		List<User> alluser = new ArrayList<User>();
		for (User u : users) {
			Account account = accountService.getRepository().findByUser(u);
			if (account != null) {
				String role = account.getRole().getName();
				if (role.indexOf(roleName) != -1) {
					alluser.add(u);
				}
			}

		}
		return alluser;
	}

	@Override
	public User findByEmpId(String empId) {
		return userRepository.findByEmpId(empId);
	}

}
